#!/usr/bin/python
from splinter import Browser
from data_validation.xss_test import XSS_Attack
from data_validation.sql_test import SQL_Injection
import threading
import sqlite3
from Queue import Queue


class Vulnerabilityscan_Thread(threading.Thread):
    
    def __init__(self,scheduler):
        threading.Thread.__init__(self)
        self.browser=Browser("phantomjs")
        self.scheduler=scheduler
        
    def detectVuln(self,url):
        xss=XSS_Attack(self.browser,url)
        xss.start()
        sql=SQL_Injection(self.browser,url) 
        sql.start()
    
    def run(self):

        while not self.scheduler.checkEmpty():
            url=self.scheduler.getLink().lower()
            if len(url)>1:
                self.detectVuln(url)

class ScanScheduler(object):
    
    def __init__(self):
        self.queue=Queue()
        conn=sqlite3.connect("webcrawler")
        cur=conn.cursor()
        cur.execute("select link from scan")
        res=cur.fetchall()
        for item in res:
            self.queue.put(item[0])
        
    def getLink(self):
        if not self.queue.empty():
            return self.queue.get()
        else:
            return False
    
    def checkEmpty(self):
        if self.queue.empty():
            return True
        else:
            return False
    
    def schedule(self,thread_size=5):
        threads=[]
        for i in range(thread_size):
            t = Vulnerabilityscan_Thread(self)
            threads.append(t)
            
        for i in range(thread_size):
            threads[i].start()
            
        for i in range(thread_size):
            threads[i].join()





        
        

        
    
    